package com.ruoyi.common.core.argument;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * <p>
 * 作用：参数解析器
 * </p>
 *
 * @author zhanglianbao
 * @since 2025-04-18 22:46
 */
public class LocalDateArgumentResolver implements HandlerMethodArgumentResolver {

  private final DateTimeFormatter formatter;

  public LocalDateArgumentResolver(String datePattern) {
    this.formatter = DateTimeFormatter.ofPattern(datePattern);
  }
  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.getParameterType().equals(LocalDate.class);
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    String paramValue = webRequest.getParameter(parameter.getParameterName());
    if (paramValue == null || paramValue.isEmpty()) {
      return null;
    }
    return LocalDate.parse(paramValue, formatter);
  }
}
